package com.itmuch.core.jsr349;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.util.StringUtils;

public class PasswordCheckValidator implements ConstraintValidator<PasswordCheck, PasswordVo> {
    @Override
    public void initialize(PasswordCheck constraintAnnotation) {
    }

    @Override
    public boolean isValid(PasswordVo subject, ConstraintValidatorContext context) {
        if (subject == null) {
            return true;
        }

        //没有填密码
        if (!StringUtils.hasText(subject.getPassword())) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("密码为空").addPropertyNode("password").addConstraintViolation();
            return false;
        }

        //两次密码不一样
        if (!subject.getPassword().trim().equals(subject.getPassword2().trim())) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("两次密码不同.").addPropertyNode("password2").addConstraintViolation();
            return false;
        }
        return true;
    }
}
